<template>
    <div>
      <DynamicTable
        :search="false"
        :data-request="loadTableData"
        :columns="columns"
        :expanded-row-keys="expandedRowKeys"
        @expand="handleExpand"
      >
        <template #toolbar>
          <a-button type="primary" @click="openModal({})"> <PlusOutlined />新增 </a-button>
          <a-button type="primary" @click="handleExpandAndClose()"
            ><SwapOutlined /> 展开/折叠
          </a-button>
        </template>
      </DynamicTable>
    </div>
  </template>
  
  <script lang="tsx" setup>
    import { ref, h,reactive,unref,defineComponent } from 'vue';
    import { cloneDeep, uniq } from 'lodash-es';
    import { message } from 'ant-design-vue';
    import { PlusOutlined, SwapOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
    import {
      baseColumns,
      formatFormSortTree,
      type TableListItem,
      type TableColumnItem,
    } from '@/views/organization/orgs/columns';
    import type { FormInstance } from 'ant-design-vue';
    import type { TreeSelectProps } from 'ant-design-vue';
    import { getOrgList, createOrg, updateOrg,deleteOrg } from '@/api/organization/orgs/orgs';
    import { useTable } from '@/components/core/dynamic-table';
    import { flatTree, type TreeDataItem } from '@/core/permission/utils';
    import { useModal } from '@/hooks/useModal/useModal';
    import OrgDetail from '@/views/organization/orgs/orgDetail.vue';
    import { orgBlankData } from '@/views/organization/orgs/orgSchmemas';
  
    defineOptions({
      name: 'SysOrgs',
    });
    defineComponent({
      OrgDetail
    })
  
    const formSortTree = ref<TreeSelectProps['treeData']>([]);
    const [DynamicTable, dynamicTableInstance] = useTable({
      pagination: false,
      size: 'small',
      rowKey: 'id',
      bordered: true,
      scroll:{
        x:true
      }
    });
    const [ModalRender, modalRef] = useModal();
    //form
    const orgInfoRef = ref<FormInstance>();
    const hasExpandKeys = ref<string[]>([]);
    const expandedRowKeys = ref<string[]>([]);
    const handleExpandAndClose = () => {
      if (expandedRowKeys.value.length) {
        expandedRowKeys.value = [];
      } else {
        expandedRowKeys.value = hasExpandKeys.value.map((i) => i);
      }
    };
    const handleExpand = (expanded, record) => {
      if (expanded) {
        expandedRowKeys.value.push(record.id);
      } else {
        const _index = expandedRowKeys.value.findIndex((item) => item == record.id);
        expandedRowKeys.value.splice(_index, 1);
      }
    };
  
    const loadTableData = async (params) => {
      const data = await getOrgList();
      const flatTreeData = flatTree(data.result);
      hasExpandKeys.value = uniq(
        flatTreeData
          .filter((item) => item.parentId && item.parentId != '0')
          .map((item) => item.parentId),
      );
      formSortTree.value = formatFormSortTree(cloneDeep(flatTreeData), '0');
      return { list: formatFormSortTree(cloneDeep(flatTreeData), '0') };
    };
  /**
     * @description 打开弹窗
     */
    const editDrawerBindValue = reactive({
      orgTree: [],
      orgItem: {},
    });
    const openModal = async (record: Partial<TableListItem> = {}) => {
      editDrawerBindValue.orgTree=ref([{ value: '0', label: '主目录', children: formSortTree.value }]);
      editDrawerBindValue.orgItem=record.id?{...record}:{...orgBlankData};
 
      ModalRender.show({
        title: `${record.id ? '编辑' : '新增'}机构`,
        width: '60%',
        destroyOnClose: true,
        bodyStyle:{ maxHeight: '60vh', overflowY: 'auto' },
        content: () => {
          return <OrgDetail ref={orgInfoRef} defaultData={unref(editDrawerBindValue)}></OrgDetail>;
        },
        // 确定方法执行
        onOk: async () => {
          const [orgInfo,orgRef] = await orgInfoRef.value?.handleSubmit();
          let res = await orgRef.value.validate()
          if (res) {
            const createOrgData=copyMatchingKeys(orgInfo, orgBlankData);
            if(createOrgData.parentId!==undefined&&createOrgData.parentId.length>0&&Array.isArray(createOrgData.parentId)){
              const orgStr=createOrgData.parentId.map(item=>item.toString());
              const parentId=orgStr.join(',');
              createOrgData.parentId=parentId;
            }
            createOrgData.id=record.id ? record.id:"";
            
            const result=await (record.id? updateOrg :createOrg)(createOrgData);
            if(result.error===200){
              const msg=record.id ? "修改成功":"新增成功";
              message.success(msg);
              dynamicTableInstance?.reload();
            }
          };
        },
      });
    };
    const delRowConfirm = async (record: TableListItem) => {
      await deleteOrg({ id: record.id });
      dynamicTableInstance.reload();
    };
    //赋值数据
    function copyMatchingKeys<T, U>(source: T, target: U): U {
      Object.keys(source).forEach(key => {
        if (key in target) {
            (target as any)[key] = source[key];
        }
      });
      return target;
    }
    const columns: TableColumnItem[] = [
      ...baseColumns,
      {
        title: '操作',
        width: 300,
        dataIndex: 'ACTION',
        hideInSearch: true,
        align: 'center',
        // fixed:'right',
        actions: ({ record }) => [
          {
            label: '编辑',
            icon: h(EditOutlined),
            onClick: () => openModal(record),
          },
          {
            label: '删除',
            danger: true,
            icon: h(DeleteOutlined),
            popConfirm: {
              title: '你确定要删除吗？',
              onConfirm: () => delRowConfirm(record),
            },
          },
        ],
      },
    ];
  </script>
  